<template>
  <div class="register">
    <Header title="注册" />
    <div class="img">注册</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          color="#ffc400"
        >
          注册账号
        </van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" color="#ffc400" @click="toLogin">
          已有账号去登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import Header from "../../components/Header.vue";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { onBeforeMount } from "@vue/runtime-core";
export default {
  components: {
    Header,
  },
  setup() {
    let router = useRouter();
    let data = reactive({
      username: "",
      password: "",
    });
    //获取浏览器数据
    const getList = () => {
      return JSON.parse(localStorage.getItem("userInfoList"));
    };
    //注册的逻辑
    const register = (value) => {
      Toast("注册成功");
      let userInfoList = getList();
      userInfoList.push(value);
      //   console.log(userInfoList);
      localStorage.setItem("userInfoList", JSON.stringify(userInfoList));
      router.push("./login");
    };

    //注册提交按钮
    const onSubmit = (value) => {
      let userInfo = getList();
      let go = true;
      console.log(userInfo);
      if (userInfo.length) {
        userInfo.forEach((item) => {
          if (item["用户名"] === value["用户名"]) {
            Toast.fail("该用户已经存在");
            go = false;
            return;
          }
        });
        if (go) {
          register(value);
        }
      } else {
        register(value);
      }
    };
    //去登录页面
    const toLogin = () => {
      router.push("./login");
    };
    //生命钩子
    //初始化本地数据
    onBeforeMount(() => {
      let initList = getList();
      localStorage.setItem(
        "userInfoList",
        JSON.stringify(initList === null ? [] : initList)
      );
    });
    return {
      ...toRefs(data),
      onSubmit,
      toLogin,
    };
  },
};
</script>

<style lang="less" scoped>
.register {
  .img {
    width: 200px;
    height: 200px;
    background-color: #bcc6f8;
    font-size: 80px;
    line-height: 200px;
    text-align: center;
    border-radius: 40px;
    margin: 20px auto;
  }
  .login {
    margin-top: 20px;
  }
}
</style>